package com.binguo.helper;

import com.alibaba.fastjson.JSON;
import com.binguo.common.exception.ServiceException;
import com.binguo.entity.FaceConfidence;
import com.binguo.entity.FaceConfidenceV2;
import com.qcloud.image.ImageClient;
import com.qcloud.image.request.FaceDelPersonRequest;
import com.qcloud.image.request.FaceDetectRequest;
import com.qcloud.image.request.FaceIdentifyRequest;
import com.qcloud.image.request.FaceNewPersonRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import static com.binguo.common.exception.ErrorCode.PERSON_EXISTS;
import static com.binguo.common.exception.ErrorCode.UPLOAD_ERROR;

/**
 * Created by haibang on 18/5/12.
 */
@Component
public class FaceHelperV2 {

    private static Logger logger = LoggerFactory.getLogger(FaceHelperV2.class);


//    @Value("youtu.appid")
//    private String APP_ID;
//    @Value("youtu.secretID")
//    private String SECRET_ID;
//    @Value("youtu.secretKey")
//    private String SECRET_KEY;
//    @Value("youtu.userId")
//    private String USER_ID;


    String appId = "1257123484";
    String secretId = "AKIDud6KAoFVVHrDLFCLYXIp8B0aCZpql7NN";
    String secretKey = "tXv3wZ0B9sMwNacR2PYUCftsfDk49yYs";
    String bucketName = "";

    //fixme haibang 1.只能新建一个person，添加该个体的其他图片调用http://api.youtu.qq.com/youtu/api/addface
    //fixme haibang 2.personId 为groupId_customerId,确保唯一性




    /**
     * 创建人脸识别信息
     * personId 为groupId_customerId,确保唯一性
     * @return faceId
     */
    public String newPerson(String url, String personId, String groupId){

        try {
            ImageClient imageClient = new ImageClient(appId, secretId, secretKey, ImageClient.NEW_DOMAIN_recognition_image_myqcloud_com);

            String[] addFaceUrlList = new String[1];
            addFaceUrlList[0] = groupId;

            FaceNewPersonRequest personNewReq = new FaceNewPersonRequest(bucketName, personId, addFaceUrlList, url, "", "");
            String res = imageClient.faceNewPerson(personNewReq);

            JSONObject object = _handleResponse(res);
            return (String)object.get("face_id");
        } catch (Exception e) {
            throw new ServiceException(UPLOAD_ERROR);
        }
    }

    /**
     * 人脸识别
     * @return 候选人
     */
    public FaceConfidenceV2 faceIdentify(String url, String groupId){
        ImageClient imageClient = new ImageClient(appId, secretId, secretKey, ImageClient.NEW_DOMAIN_recognition_image_myqcloud_com);

        FaceIdentifyRequest faceIdentifyReq = new FaceIdentifyRequest(bucketName, groupId, url);// 一个 groupId
        //FaceIdentifyRequest  faceIdentifyReq = new FaceIdentifyRequest(bucketName, groupIds, faceImageUrl);// 多个 groupId
        JSONObject object = _handleResponse(imageClient.faceIdentify(faceIdentifyReq));
        return JSON.parseObject(object.toString(), FaceConfidenceV2.class);
    }

    /**
     *
     * 删除个体
     * @return
     */
    public void deletePerson(String persionId){
        try{
            ImageClient imageClient = new ImageClient(appId, secretId, secretKey, ImageClient.NEW_DOMAIN_recognition_image_myqcloud_com);

            FaceDelPersonRequest delPersonReq = new FaceDelPersonRequest(bucketName, persionId);

            _handleResponse(imageClient.faceDelPerson(delPersonReq));
        } catch (Exception e){
            e.printStackTrace();
        }



    }




    private JSONObject _handleResponse(String res){
        try {
            JSONObject response = new JSONObject(res);
            Integer code = (Integer) response.get("code");
            String msg = (String) response.get("message");
            if(code == 0) {
                return response.getJSONObject("data");
            }else if(code == -1302){
                throw new ServiceException(PERSON_EXISTS);
            } else {
                logger.info("腾讯人脸response发现错误, errorcode:" + code + ", errormsg: " + msg);
                throw new ServiceException(msg);
            }
        } catch (JSONException e) {
            throw new ServiceException(UPLOAD_ERROR);
        }
    }


    /**
     * 检测人脸质量
     * personId 为groupId_customerId,确保唯一性
     * @return faceId
     */
    public String detectFace(String url){
        ImageClient imageClient = new ImageClient(appId, secretId, secretKey, ImageClient.NEW_DOMAIN_recognition_image_myqcloud_com);
        try {
            FaceDetectRequest faceDetectRequest = new FaceDetectRequest(bucketName, url, 1);
            String res = imageClient.faceDetect(faceDetectRequest);

            System.out.println(res);
            JSONObject object = _handleResponse(res);
            return (String)object.get("face_id");
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
            throw new ServiceException(UPLOAD_ERROR);
        }
    }

    public static void main(String[] args) {

        String url = "http://img.binguoai.com/2e3dfd35-0ea1-ef62-96f2-d35c38bed428.png";
        FaceHelperV2 faceHelperV2 = new FaceHelperV2();

        faceHelperV2.detectFace(url);
//        新建个体
//        String a = faceHelperV2.newPerson(url, "test8", "test5");



//        FaceConfidenceV2 faceConfidenceV2 =   faceHelperV2.faceIdentify(url, "test5");
//        System.out.println(faceConfidenceV2);
//        faceHelperV2.deletePerson("test8");

    }
}
